package es.juanc.xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ValidateXmlByXsd {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// Constantes para validacion de Schemas   
		 final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";  
		 final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";  
		 final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";  
		 final String MY_SCHEMA = "xml/validateXML.xsd";  
		 final String MY_XML= "xml/validateXML.xml";  
		                           
		 // Creando la factoria e indicando que hay validacion  
		 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();  
		 documentBuilderFactory.setNamespaceAware(true);  
		 documentBuilderFactory.setValidating(true);  
		           
		 try {  
		     
		   //Configurando el Schema de validacion          
		   documentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);  
		   documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE, new File(MY_SCHEMA));  
		             
		   // Parseando el documento  
		   DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();  
		   documentBuilder.setErrorHandler( new ErrorHandler(){
				public void error(SAXParseException exception) throws SAXException {
					System.out.println( "error: La cagamos" );		
				}
				public void fatalError(SAXParseException exception) throws SAXException {
					System.out.println( "fatalError: La cagamos" );		
				}
				public void warning(SAXParseException exception) throws SAXException {
					System.out.println( "warning: La cagamos" );		
				}				
			});  
		     
		   //Document parse = 
		   documentBuilder.parse(new File(MY_XML));  
		   
		   System.out.println("El documento está bien formado y es válido");
		   
		} catch (SAXException saxEx){  
			System.out.println( "SAXException: La cagamos" );		
		} catch (Exception ex) {
			System.out.println( "Exception: La cagamos" );		
		}
	}
}

class ParserErrorHandler implements ErrorHandler {

	public void error(SAXParseException exception) throws SAXException {
		System.out.println( "error: La cagamos" );		
	}

	public void fatalError(SAXParseException exception) throws SAXException {
		System.out.println( "fatalError: La cagamos" );		
	}

	public void warning(SAXParseException exception) throws SAXException {
		System.out.println( "warning: La cagamos" );		
	}
	
}